import {
  getInspectTaskByPage,
  addInspectTask,
  updateInspectTask,
  delInspectTask,
  closeInspectTask,
} from '@/services/device/inspectTask';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { tableSearchPublicConfig } from '@/utils/filterUtils';
import { Button, Col, Form, Input, message, Modal, Row, Tree } from 'antd';
import { sortTran, filterTran } from '@/utils/requestUtil';
import React, { useEffect, useImperativeHandle, useRef, useState } from 'react';
import { getErrorReportMembers } from '@/services/platform/errorReport';
import {
  ModalForm,
  PageHeaderWrapper,
  ProFormDatePicker,
  ProFormText,
} from '@ant-design/pro-components';
import InspectItem from '@/pages/device/inspectItem';
const InspectTask: React.FC<{}> = (props) => {
  const actionRef = useRef<ActionType>();
  const ref = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [modalVisit1, setModalVisit1] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [formTitle1, setFormTitle1] = useState(); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [currentTaskId, setCurrentTaskId] = useState(); //当前巡检计划Id
  const [clickInspectId, setClickInspectId] = useState();
  const [form] = Form.useForm();
  const [inspectMember, setInspectMember] = useState(); //巡检人信息

  /* 声明周期钩子，用于获取父组件出入值 */
  React.useEffect(() => {
    getInspectMemberInfo();
  }, []);

  /*  使用 useImperativeHandle 将 actionRef 暴露给父组件，让父组件可以拿到子组件的刷新关键词ref */
  // useImperativeHandle(subRef, () => {});
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
      align: 'center',
      sorter: true,
    },
    {
      title: '巡检单编号',
      dataIndex: 'inspectId',
      align: 'center',
      sorter: true,
    },
    {
      title: '巡检描述',
      dataIndex: 'taskDesc',
      align: 'center',
      sorter: true,

      ellipsis: true,
    },
    {
      title: '巡检任务号',
      dataIndex: 'taskId',
      align: 'center',
      sorter: true,
      search: false,
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      hideInTable: true,
      align: 'center',
      sorter: true,

      search: false,
    },
    {
      title: '完成时间',
      dataIndex: 'finishedTime',
      hideInTable: true,
      align: 'center',
      sorter: true,

      search: false,
    },
    {
      title: '巡检执行人',
      dataIndex: 'inspectBy',
      align: 'center',
      sorter: true,
      valueType: 'select',
      fieldProps: {
        options: inspectMember,
      },
    },
    {
      title: '巡检申报人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
      align: 'center',
      sorter: true,
    },
    {
      title: '生成日期', //表头显示的名称
      search: false,
      dataIndex: 'createTime',
      align: 'center',
      sorter: true,
    },
    {
      title: '计划日期',
      dataIndex: 'planedTime',
      align: 'center',
      sorter: true,
      valueType: 'date',
    },
    {
      title: '执行人',
      dataIndex: 'taskBy',
      hideInTable: true,
      align: 'center',
      sorter: true,

      search: false,
    },

    {
      title: '状态',
      dataIndex: 'taskState',
      align: 'center',
      sorter: true,
      fieldProps: {
        options: [
          {
            label: '未完成',
            value: '未完成',
          },
          {
            label: '已完成',
            value: '已完成',
          },
        ],
      },
    },
    {
      title: '超时标记',
      dataIndex: 'timeOut',
      hideInTable: true,
      align: 'center',
      sorter: true,

      search: false,
    },
    {
      title: '唯一标识',
      dataIndex: 'uniqueIdentifier',
      hideInTable: true,
      align: 'center',
      sorter: true,

      search: false,
    },
    {
      title: '更新人',
      dataIndex: 'updateBy',
      hideInTable: true,
      align: 'center',
      sorter: true,

      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      align: 'center',

      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            setModalVisit1(true);
            setFormTitle1('巡检任务明细');
            setCurrentTaskId(record.taskId);
          }}
        >
          执行
        </a>,
        <a
          key="editKey"
          hidden={record.taskState === '已完成'}
          onClick={() => {
            setModalVisit(true);
            setCreateOrUpdate(false);
            setFormTitle('编辑');
            form.setFieldsValue({
              createBy: record.createBy,
              finishedTime: record.finishedTime,
              inspectBy: record.inspectBy,
              inspectId: record.inspectId,
              planedTime: record.planedTime,
              taskBy: record.taskBy,
              taskDesc: record.taskDesc,
              taskId: record.taskId,
              taskState: record.taskState,
              timeOut: record.timeOut,
              uniqueIdentifier: record.uniqueIdentifier,
              updateBy: record.updateBy,
              id: record.id,
              createTime: record.createTime,
              createName: record.createName,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delInspectTask({ id: record.id });
                actionRef.current.reload();
              },
            });
          }}
        >
          删除
        </a>,
        <a
          key="editKey"
          hidden={record.taskState === '已完成'}
          onClick={() => {
            closeTask(record);
            actionRef.current?.reload();
          }}
        >
          关闭
        </a>,
      ],
    },
  ];
  /* 巡检计划任务关闭功能 */
  const closeTask = async (values: any) => {
    try {
      const result = await closeInspectTask(values);
      if (result.message === 'success') {
        message.success('关闭巡检计划任务成功！');
      } else {
        message.error('关闭巡检计划任务失败！');
      }
    } catch (error) {
      console.log('Error', error);
    }
  };

  const handleSubmit = async (values) => {
    setConfirmLoading(true);
    if (formTitle == '新建') {
      const result = await addInspectTask(values);
      if (result != null) {
        message.success('添加成功');
      }
    } else {
      await updateInspectTask(values);
    }
    setConfirmLoading(false);
    setModalVisit(false);
    actionRef.current.reload();
  };
  /* 获取巡检人信息 */
  const getInspectMemberInfo = async () => {
    try {
      const errorReportMembersArray = await getErrorReportMembers?.(null);
      setInspectMember(
        errorReportMembersArray.data?.map((item: any) => {
          return { value: item.name, label: item.name };
        }),
      );
      console.log('异常处理人列表：', errorReportMembersArray);
    } catch (e) {
      console.log('获取巡检人接口报错', e);
      message.error('未正常获取巡检人信息');
    }
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="巡检任务查询"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        search={tableSearchPublicConfig}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            onClick={() => {
              setClickInspectId(undefined);
            }}
            type="primary"
          >
            重置
          </Button>,
          // <Button
          //   key="button"
          //   icon={<PlusOutlined />}
          //   onClick={() => {
          //     setCreateOrUpdate(false);
          //     setFormTitle('新建');
          //     form.resetFields();
          //     setModalVisit(true);
          //   }}
          //   type="primary"
          // >
          //   新建
          // </Button>,
          // <Button
          //   key="button"
          //   icon={<PlusOutlined />}
          //   onClick={() => {
          //     const filters = filterTran(ref.current.getFieldsValue());
          //     exportInspectTask({
          //       current: 1,
          //       pageSize: 5000,
          //       filters: filters,
          //     }).then((res) => {
          //       const aLink = document.createElement('a');
          //       document.body.appendChild(aLink);
          //       aLink.style.display = 'none';
          //       aLink.href = window.URL.createObjectURL(res);
          //       aLink.setAttribute('download', `InspectTask.xlsx`);
          //       aLink.click();
          //       document.body.removeChild(aLink);
          //     });
          //   }}
          //   type="primary"
          // >
          //   导出
          // </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          console.log(clickInspectId);
          const sorters = sortTran(sort);
          const filters = filterTran(params);
          // const filters = [
          //   {
          //     andOr: 'and',
          //     field: 'inspectId',
          //     operator: 'eq',
          //     value: clickInspectId,
          //   },
          //   {
          //     andOr: 'and',
          //     field: 'taskState',
          //     operator: 'eq',
          //     value: taskState,
          //   },
          // ];
          const result = await getInspectTaskByPage({
            ...params,
            sorters: sorters,
            filters: filters,
          });
          result?.data?.content.map((item: any) => {
            item.createTime = item.createTime.split(' ')[0];
          });
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        scroll={{ x: 2000, y: 350 }}
        pagination={{
          defaultPageSize: 100,
          defaultCurrent: 1,
          pageSizeOptions: [100, 500, 1000],
          showSizeChanger: true,
        }}
        rowSelection={{}}
      />

      <ModalForm
        visible={modalVisit}
        title={formTitle}
        form={form}
        onFinish={handleSubmit}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setModalVisit(false);
          },
        }}
        initialValues={{
          uniqueIdentifier: '巡检计划任务',
        }}
      >
        <ProFormText name="id" label="id" placeholder="请输入名称" hidden={true} />
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormText
              name="inspectId"
              label="巡检单编号"
              rules={[{ required: true, message: '请输入巡检单编号!' }]}
              disabled={true}
            />
          </Col>
          <Col span={12}>
            <ProFormText
              name="taskId"
              label="巡检任务号"
              rules={[{ required: true, message: '请输入巡检任务号!' }]}
              disabled={true}
            />
          </Col>
        </Row>
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormText
              name="taskDesc"
              label="巡检描述"
              rules={[{ required: true, message: '请输入巡检描述!' }]}
              disabled={createOrUpdate}
            />
          </Col>
          <Col span={12}>
            <ProFormText
              name="taskState"
              label="状态"
              rules={[{ required: true, message: '请输入状态!' }]}
              disabled={true}
            />
          </Col>
        </Row>
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormText
              name="inspectBy"
              label="巡检执行人"
              rules={[{ required: true, message: '请输入巡检执行人!' }]}
              disabled={createOrUpdate}
            />
          </Col>
          <Col span={12}>
            <ProFormText
              name="createName"
              label="巡检申报人"
              rules={[{ required: true, message: '请输入巡检申报人!' }]}
              disabled={true}
            />
          </Col>
        </Row>
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormText
              name="createTime"
              label="生成日期"
              rules={[{ required: true, message: '请输入生成时间!' }]}
              disabled={true}
            />
          </Col>
          <Col span={12}>
            <ProFormDatePicker
              name="planedTime"
              label="计划日期"
              width={'100%'}
              rules={[{ required: true, message: '请输入计划时间!' }]}
              disabled={createOrUpdate}
            />
          </Col>
        </Row>
        <ProFormText name="taskBy" label="执行人" disabled={createOrUpdate} hidden={true} />
        <ProFormText name="timeOut" label="超时标记" disabled={createOrUpdate} hidden={true} />
        <ProFormText
          name="uniqueIdentifier"
          label="唯一标识"
          // rules={[{ required: true, message: '请输入 your uniqueIdentifier!' }]}
          disabled={createOrUpdate}
          hidden={true}
        />
        <ProFormText
          name="updateBy"
          label="更新人"
          // rules={[{ required: true, message: '请输入 your updateBy!' }]}
          disabled={createOrUpdate}
          hidden={true}
        />
      </ModalForm>
      {/* 巡检详情模块 */}
      <Modal
        open={modalVisit1}
        title={formTitle1}
        destroyOnClose
        width={1500}
        onCancel={() => {
          setModalVisit1(false);
        }}
        footer={[]}
      >
        {/* 巡检详细模块组件 */}
        <InspectItem taskId={currentTaskId} />
      </Modal>
    </PageHeaderWrapper>
  );
};
export default InspectTask;
